import axios, {AxiosInstance} from 'axios';

const service:AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_XXX_SERVICE_URL as string, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
});


function loadInterceptors(interceptors: any, options: any) {
  const {request, response} = interceptors;
  request.forEach((item:any) => {
    let {onFulfilled, onRejected} = item
    if (!onFulfilled || typeof onFulfilled !== 'function') {
      onFulfilled = (config:any) => config
    }
    if (!onRejected || typeof onRejected !== 'function') {
      onRejected = (error:any) => Promise.reject(error)
    }
    service.interceptors.request.use(
      config => onFulfilled(config, options),
      error => onRejected(error, options)
    )
  })

  response.forEach((item:any) => {
    let { onFulfilled, onRejected } = item
    if(!onFulfilled || typeof onFulfilled !== 'function') {
      onFulfilled = (config:any) => config
    }

    if(!onRejected || typeof onRejected !== 'function') {
      onRejected = (error: any) => Promise.reject(error)
    }

    service.interceptors.response.use(
      config => onFulfilled(config, options),
      error => onRejected(error, options)
    )
  })

}


export {
  service,
  loadInterceptors
}


